//
//  ComposeViewController.swift
//  SinaWeiBo
//
//  Created by tuyue on 16/3/16.
//  Copyright © 2016年 xueyang.co.ltd. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD


class ComposeViewController: UIViewController {
    
    
    //MARK: - 表情按钮点击调取方法
    @objc private func selectEmoticon(){
    print("hahahh")
    }
    
    
    //MARK: - 点击选择图片调取方法
    @objc private func selectPicture(){
    UIView.animateWithDuration(0.25) { () -> Void in
        self.picSelectVC.view.snp_updateConstraints(closure: { (make) -> Void in
            make.height.equalTo( ScreenHeight / 3 * 2 )
        })
        }
    }
    
    
    //MARK: - 点击关闭调取方法
    @objc private func closeComposeView(){
        print("hahahh")
        //销毁当前控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    //MARK: - 发布按钮点击调取方法
    @objc private func sendMessageWeibo(){
        //字符串保存发布微博的接口的网址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        /**判断token是否过期吗、，如果过期就返回*/
        guard let token = UserAccount.sharedAccount.access_token else{
            print("用户未登录，或登陆过期")
            return
        }
        /**设置参数*/
        let parameters = ["access_token" : token , "status":textView.text]
         HTTPClient.sharedHttpClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            //错误的展示
            if error != nil {
            SVProgressHUD.showErrorWithStatus("微博发布失败")
                return
            }
            //正确的展示
            SVProgressHUD.showSuccessWithStatus("微博发布成功")
            //调取销毁当前控制器的方法
            self.closeComposeView()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
//        view.backgroundColor = UIColor.greenColor()
        /**在控制器加载时调取注册通知*/
        registerNotification()
        
    }
    //MARK: - 接收通知
    @objc private func KeyboardChange(n:NSNotification){
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 必须将结构体转化为NSValue类型才能存进字典中
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offSet = -ScreenHeight + rect.origin.y
         /**给toolBar添加一个动画，使其能够与keyB弹出保持同步*/
        UIView.animateWithDuration(duration) { () -> Void in
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(offSet)
            })
            /**强制刷新*/
            self.view.layoutIfNeeded()
        }
       
        
    }
    
    //MARK: - 注册通知
    private func registerNotification(){
    NSNotificationCenter.defaultCenter().addObserver(self , selector: "KeyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //MARK: - 移除通知
    deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    
    /**懒加载实例化一个文本输入视图*/
    private lazy var textView:UITextView  = {
        let tv = UITextView()
        tv.backgroundColor = UIColor(white: 0.93, alpha: 0.8)
        tv.textColor = textColor
        tv.font = UIFont.systemFontOfSize(18)
        tv.delegate = self
        /**设置拽动时，让键盘消失*/
        tv.keyboardDismissMode = .OnDrag
        /**设置scrollView中 垂直方向可以拽动，设置可以划出边界*/
        tv.alwaysBounceVertical = true
        return tv
    }()
    
    /**设置textView中占位文本*/
    private lazy var placeholderLabel:UILabel = UIFactory.factoryLable("#请在此处输入文字", fontSize: 18, textColor: UIColor.lightGrayColor())
    
    /**懒加载实例化toolBar*/
    private var toolBar:UIToolbar = UIToolbar()
    
    /**懒加载创建图片选择器视图pictureSelectorViewController*/
    private var picSelectVC: PictureSelectorController = PictureSelectorController()
}




//MARK: - ComposeViewController类扩展以及遵守TextView的代理
extension ComposeViewController : UITextViewDelegate{
    /**记录，当textView改变是调用此方法*/
    func textViewDidChange(textView: UITextView) {
        /**占位Label隐藏*/
        placeholderLabel.hidden = textView.hasText()
        /**关闭按钮可与用户交互*/
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
}




//MARK: - 类扩展 该方法中 主要做添加子视图，设置约束
extension ComposeViewController{
    private func setupUI(){
        setNavBar()
        setTextView()
        setToolBar()
        setSelectorPictureViewController()
        self.view.bringSubviewToFront(toolBar)
    }
    
    //MARK: - 设置图片选择器SelectPictureViewController
    private func setSelectorPictureViewController() {
    addChildViewController(picSelectVC)
        view.addSubview(picSelectVC.view)
        
        picSelectVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(0)
        }
        
}
    
    
    //MARK: - 设置toolBar
    private func setToolBar(){
    /**添加到View*/
    view.addSubview(toolBar)
        /**设置toolBar的约束*/
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(self.view)
        }
        
        /**创建一个UIBarButtonItem的实例变量*/
        var items = [UIBarButtonItem]()
        /**创建字典数组，用来存放item的图片名*/
        let itemSettings = [["imageName" : "compose_toolbar_picture", "actionName" :  "selectPicture"],["imageName" :  "compose_mentionbutton_background"],["imageName" : "compose_trendbutton_background"],["imageName" : "compose_emoticonbutton_background","actionName" : "selectEmoticon"],["imageName" : "compose_add_background"]]
        
        for item in itemSettings {
        /**创建常量保存字典中Key对应的Value值*/
        let imageName = item["imageName"]
            /**设置创建btn并设置图片*/
        let btn = UIFactory.factoryButtonWithImage(imageName, backImageName: nil)
            /**给btn添加点击事件*/
            if let actionName = item["actionName"] {
            btn.addTarget(self, action:Selector(actionName), forControlEvents: .TouchUpInside)
            }
            /**将btn添加到barButtonItem中的customView中，并创建常量保存*/
            let barItem = UIBarButtonItem(customView: btn)
            /**将其添加到数组*/
            items.append(barItem)
            /**添加弹簧效果，使得item可以均匀的分开*/
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        /**将遍历的值赋给toolBar的items中*/
        toolBar.items = items
        
    }
    

    
    
    //MARK: - 设置TextView
    private func setTextView(){
        /**添加到父视图*/
        view.addSubview(textView)
        /**设置textView的约束*/
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight/3)
        }
        /**添加到textVIew*/
        /**设置占位图片约束*/
        textView.addSubview(placeholderLabel)
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
    }
    
    
    
    
    
    //MARK: - 设置NavBar
    private func setNavBar(){
        //设置navBar的左键
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeComposeView")
        //设置navBar的右键
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "sendMessageWeibo")
        //设置右键赞不允许与用户交互，当文本框中有内容时候才可以交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        //MARK: - 设置文案View
        let myInfoView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        //将文案View添加到NavBar
        navigationItem.titleView = myInfoView
        
        /**创建文案Label*/
         //标题label
        let titleLabel = UIFactory.factoryLable("我的微博", fontSize: 18, textColor: textColor)
        //昵称label
        let nameLabel = UIFactory.factoryLable(UserAccount.sharedAccount.name!, fontSize: 14, textColor: textColor)
        
        //添加约束到myInfoView
        myInfoView.addSubview(titleLabel)
        myInfoView.addSubview(nameLabel)
        /**设置标题约束*/
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myInfoView.snp_top)
            make.centerX.equalTo(myInfoView.snp_centerX)
            
        }
        /**设置昵称约束*/
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(myInfoView.snp_bottom)
            make.centerX.equalTo(myInfoView.snp_centerX)
        }
    }
}





